package com.wzg.ftpstresstool.config;

import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@ConfigurationPropertiesBinding
public class FileSizeConverter implements Converter<String, Long> {
    
    private static final Pattern FILE_SIZE_PATTERN = Pattern.compile("^(\\d+(\\.\\d+)?)\\s*(B|KB|MB|GB|TB)?$", Pattern.CASE_INSENSITIVE);
    
    @Override
    public Long convert(String source) {
        return parseSize(source);
    }
    
    public static long parseSize(String source) {
        if (source == null || source.isEmpty()) {
            return 0L;
        }
        
        Matcher matcher = FILE_SIZE_PATTERN.matcher(source.trim());
        if (matcher.matches()) {
            double value = Double.parseDouble(matcher.group(1));
            String unit = matcher.group(3);
            
            if (unit == null || unit.equalsIgnoreCase("B")) {
                return (long) value;
            } else if (unit.equalsIgnoreCase("KB")) {
                return (long) (value * 1024);
            } else if (unit.equalsIgnoreCase("MB")) {
                return (long) (value * 1024 * 1024);
            } else if (unit.equalsIgnoreCase("GB")) {
                return (long) (value * 1024 * 1024 * 1024);
            } else if (unit.equalsIgnoreCase("TB")) {
                return (long) (value * 1024 * 1024 * 1024 * 1024);
            }
        }
        
        // 如果不匹配模式，尝试直接解析为数字
        try {
            return Long.parseLong(source);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid file size format: " + source);
        }
    }
}